import Taro from '@tarojs/taro'
// import Amap from '@/static/lib/amap-wx'
import QQMapWX from '@/static/lib/qqmap-wx-jssdk.min.js'
import { STORE_LOCATION } from '@/store/location/action-types'
import allCity from '@/static/lib/city-data.json'
import { storeInfo } from '@/api'

const TYPE = 'gcj02'
const qqmap = new QQMapWX({ key: 'QMYBZ-LRXEW-C2VR5-RUZTZ-ISL3V-REB4S' })
// const amap = new Amap.AMapWX({ key: '7bdb6f017f3c1aa9606b1a346eddd73a' })
// 小于24小时
const isGt24h = (prevTimestamp: number, timestamp: number = +new Date()) => timestamp - prevTimestamp < 86400000
const newCityList = Object.keys(allCity).map(key => {
    return {
        chars: key,
        list: allCity[key]
    }
})
const alipayMap = {
    // 位置授权状态
    async status() {
        try {
            const result = await Taro.getSetting()
						console.log('result',result)
						let {authSetting} = result
						return authSetting.location
        } catch (e) {
            return false
        }
    },
    // 获取位置信息
    async getLocation(showLoading: boolean = false,type:number = 0) {
        //获取位置信息  return： true获取地址成功/false获取地址失败
        const locationStatus = await this.status()
        console.log('locationStatus: ', locationStatus);
        if (locationStatus) {
            if (showLoading) {
                Taro.showLoading({
                    title: '获取定位中'
                })
            }
						let data = {}
						await my.getLocation({
							type,
							success: (res) => {
								Taro.setStorageSync('LOCATION_STATUS', true)
								if (showLoading) {
										Taro.hideLoading()
								}
								data = res
							},
							fail: (error) => {
								console.log('有没有执行--fail--')
								console.log('err',error)
								Taro.setStorageSync('LOCATION_STATUS', false)
								data = !locationStatus
								// 没有授权，获取不了位置信息
								// return !locationStatus
								},
							complete: () => {
								console.log('有没有执行--complete--')
								Taro.hideLoading()
							},
						})
						return data

        } else {
					console.log('会不会执行到这里--false-locationStatus')
            Taro.setStorageSync('LOCATION_STATUS', false)
            Taro.hideLoading()
            // 没有授权，获取不了位置信息
            return locationStatus
        }
    },
    // POI搜索关键字
    search(params) {
        return new Promise((resolve, reject) => {
            qqmap.getSuggestion({
                page_size: 20,
                ...params,
                success(res) {
                    if (res.status === 0) {
                        resolve(res.data)
                    } else {
                        reject(res)
                    }
                },
                fail(err) {
                    reject(err)
                }
            })
        })

    },
    // 获取地理位置信息和poi列表
    reverseGeocoder(params: any = {}) {
        return new Promise(async (resolve, reject) => {
            try {
                const { location } = params
                let locationInfo
                if (!location) {
                    locationInfo = await this.getLocation()
                } else {
                    locationInfo = location
                }

                if (locationInfo) {
                    const { latitude, longitude } = locationInfo
                    qqmap.reverseGeocoder({
                        location: { latitude, longitude },
                        get_poi: 1,
                        poi_options: 'page_size=20;page_index=1',
                        ...params,
                        success(res) {
                            resolve(res.result)
                        },
                        fail(err) {
                            reject(err)
                        },
                        // complete: function (res) {
                        //     console.log('complete: ', res);
                        // }
                    })
                } else {
                    resolve(locationInfo)
                }
            } catch (e) {
							console.log('error',e)
                reject(e)
            }
        })
    },
    // 距离计算
    calculateDistance(params = {}) {
        return new Promise((resolve, reject) => {
            qqmap.calculateDistance({
                mode: 'driving',
                ...params,
                success(res) {
                    if (res.status === 0) {
                        resolve(res.result)
                    } else {
                        Taro.showToast({
                            icon: 'none',
                            title: res.message
                        })
                        reject(res)
                    }
                }
            })
        })
    },
    // 获取城市
    getCityList() {
        return new Promise((resolve, reject) => {
            resolve(newCityList)
        })
    },

    // 判断缓存有没有历史记录门店， true返回门店信息，false返回null
    historyStore() {
        const store = Taro.getStorageSync(STORE_LOCATION)
        if (store && store.storeName) {
            return store
        }
        return null
    },
    // 判断是否存在历史记录门店（24小时内&小于30km）
    async hasHistoryStore(location) {
        if (!location) return false
        const storeLocation = this.historyStore()
        let newStoreLocation: any = null
        if (storeLocation) {
            if (isGt24h(storeLocation.timestamp)) {
                const { latitude: userLatitude, longitude: userLongitude } = location
                const storeParams: any = {
                    storeCode: storeLocation.storeCode,
                    userLongitude,
                    userLatitude
                }
                try {
                    // 获取历史记录的门店，根据经纬度判断距离是否小于30km
                    const result = await storeInfo(storeParams)
                    const { distance } = result.data.data
                    // 小于30km,使用浏览记录数据 distance-km
                    if (Number(distance) < 30) {
                        newStoreLocation = {
                            ...result.data.data,
                            timestamp: +new Date()
                        }
                        Taro.setStorageSync(STORE_LOCATION, newStoreLocation)
                        return newStoreLocation
                    } else {
                        return newStoreLocation
                    }
                } catch (e) {
                    return newStoreLocation
                }
            } else {
                return newStoreLocation
            }
        }
        return newStoreLocation
    }
}
export {
    qqmap
}
export default alipayMap
